#! /usr/bin/lua
---------
-- ## 通过C代码实现的扩展类
--
-- Dependencies: `apm4lua`, `apm_global`
-- @module ApmExt
-- @author songbb
-- @copyright All Rights Reserved Copyright (C) 2014 - 2017 broada,Co.,Ltd.

require("apm4lua")
require("apm_global")

ApmExt = {}

--- 获取当前系统微秒时间
-- @treturn number 当前系统微秒时间，例如 1466591758985688
function ApmExt.getMicroSecond()
    return apm4report.getmicrosecond()
end

--- 获取当前系统毫秒时间
-- @treturn number 当前系统毫秒时间，例如 1466591758985
function ApmExt.getMillisecond()
    return apm4report.getmillisecond()
end

--- 字符串转UTF8格式
-- @string s_str 原始字符串
-- @string s_charset CHARSET格式，例如UTF-8
-- @treturn[1] string UTF8格式字符串
-- @return[2] nil
function ApmExt.strToUTF8(s_str, s_charset)
    if type(s_str) ~= "string" or
            type(s_charset) ~= "string" or
            s_str == nil or
            s_str == "" or
            s_charset == nil or
            s_charset == "" then
        logger:debug("parameter s_str/s_charset err")
        return nil
    end

    return apm4report.strToUTF8(s_str, s_charset)
end

--- 读取RSA私钥
-- @string s_keystring 私钥KEY内容
-- @treturn (RSA*) RSA对象指针
function ApmExt.PEMReadBIORSAPrivateKey(s_keystring)
    if s_keystring == nil or s_keystring == "" then return nil end
    return apm4report.PEMReadBIORSAPrivateKey(s_keystring)
end

--- RSA密钥解密
-- @string s_encrypted 密文
-- @tparam (RSA*) s_rsa_key RSA对象指针
-- @treturn string 明文
function ApmExt.RSAPrivateDecrypt(s_encrypted, s_rsa_key)
    if s_encrypted == nil
            or s_encrypted == ""
            or s_rsa_key == nil
    then
        return nil
    end
    return apm4report.RSAPrivateDecrypt(s_encrypted, s_rsa_key)
end

--- AES-CBC解密
-- @string s_encrypted 密文
-- @number i_encrypted_len 密文长度
-- @string s_aes_key 密钥
-- @string s_iv 16位初始向量
-- @number i_bits 密钥位数
-- @treturn string 明文
function ApmExt.AESCBCDecrypt(s_encrypted, i_encrypted_len, s_aes_key, s_iv, i_bits)
    if s_encrypted == nil
            or s_encrypted == ""
            or i_encrypted_len == nil
            or i_encrypted_len <= 0
            or s_aes_key == nil
            or s_aes_key == ""
            or s_iv == nil
            or s_iv == ""
    then
        return nil
    end

    if i_bits == nil then i_bits = 128 end

    return apm4report.AESCBCDecrypt(s_encrypted, i_encrypted_len, s_aes_key, s_iv, i_bits)
end

return ApmExt
